package servlets.message;

import hibernate.method.NewsMethods;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class AddNews
 */
@WebServlet("/AddNews")
public class AddNews extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddNews() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();

		String subject = (String) request.getParameter("subject");
		String content = (String) request.getParameter("content");

		response.setContentType("text/html");

		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		NewsMethods nm = new NewsMethods();
		nm.addNews(sessionFactory, session, subject, content);

		try {
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"News zostal dodany\"); window.location.href = \"management/index.jsp?page=main&group=news\";</script>");
		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">alert(\"News nie zostal dodany\"); window.location.href = \"management/index.jsp?page=main&group=news\";</script>");
		}

	}

}
